package com.google.incomplete.interceptors;

import com.google.incomplete.annotations.MyAnnotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import com.google.incomplete.services.VerifyService;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.util.logging.LoggerFactory;
import com.opensymphony.xwork2.util.logging.Logger;
import org.springframework.beans.BeansException;
import com.opensymphony.xwork2.spring.SpringObjectFactory;
import com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor;
import com.opensymphony.xwork2.ActionInvocation;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class MyInterceptor extends AbstractInterceptor implements ApplicationContextAware{

    private static final Logger LOG = LoggerFactory.getLogger(ActionAutowiringInterceptor.class);

    public static final String APPLICATION_CONTEXT = "com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor.applicationContext";

    private boolean initialized = false;
    private ApplicationContext context;
    private SpringObjectFactory factory;
    private Integer autowireStrategy;

    public void setAutowireStrategy(Integer autowireStrategy) {
        this.autowireStrategy = autowireStrategy;
    }

    
    @Override public String intercept(ActionInvocation invocation) throws Exception {
        //get request and response
        //HttpServletRequest request = ServletActionContext.getRequest();
        //HttpServletResponse response = ServletActionContext.getResponse();

        System.out.println("been invoked");
        Object obj = invocation.getAction();
        if (obj instanceof Action) {
            System.out.println("action");
        }
        Class cls = obj.getClass();
        Method method = cls.getMethod("execute",null);
        Annotation[] annotations = method.getAnnotations(); 
        if (annotations != null ) {
            for (Annotation anno : annotations ) {
                if (anno.annotationType().equals(MyAnnotation.class)) {
                    MyAnnotation tmp = (MyAnnotation) anno;
                    System.out.println("name is " + tmp.name());
                    System.out.println("age is " + tmp.age());
                }
            }
        }
        
        VerifyService verifyService = (VerifyService)context.getBean("verifyService");
        verifyService.verify();
        return invocation.invoke();
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    
    protected ApplicationContext getApplicationContext() {
        return context;
    }

}
